package ReentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description: ReentrantLock 锁中断
 * User: sfx
 * Date: 2022-12-27
 * Time: 15:30
 */
public class TestDemo2 {
    private static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                //调用lockInterruptibly这个方法可以进行中断进制
                //当该线程没有获取到锁的时候,可以选择不进行死等,可以让另外一个线程对当前
                //线程进行打断,触发异常之后,就可以进行一些操作-->一般是直接退出
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread()+"没有获取到锁,返回");
                return;
            }
            try {
                System.out.println(Thread.currentThread()+"获取到锁");
            }finally {
                lock.unlock();
            }
        },"t1");
        //主线程先启动,先进行加锁
        lock.lock();
        System.out.println(Thread.currentThread()+"获取锁");
        //在启动t1线程
        t1.start();
        //此时主线程获取到锁,但t1线程没有获取到锁

        Thread.sleep(2000);
        //主线程给t1线程进行打断->叫醒它,不让他等了
        t1.interrupt();
        System.out.println(Thread.currentThread()+"打断t1线程,叫醒它不让它等了");
    }
}
